package cn.lrwjz.androidguide.ui.exmple;

import android.app.AlertDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.lrwjz.androidguide.R;
import cn.lrwjz.androidguide.adapter.BillAdapter;
import cn.lrwjz.androidguide.db.BillDbHelper;
import cn.lrwjz.androidguide.model.Bill;

public class SQLiteActivity extends AppCompatActivity implements BillAdapter.OnItemClickListener {
    private BillDbHelper dbHelper;
    private BillAdapter adapter;
    private List<Bill> bills = new ArrayList<>();
    private TextInputLayout tilSearchAmount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_sqlite);

        // 设置工具栏
        MaterialToolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("SQLite 示例");
        }

        // 初始化数据库
        dbHelper = new BillDbHelper(this);

        // 设置RecyclerView
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new BillAdapter(bills, this);
        recyclerView.setAdapter(adapter);

        // 设置搜索功能
        tilSearchAmount = findViewById(R.id.til_search_amount);
        tilSearchAmount.getEditText().setOnEditorActionListener((v, actionId, event) -> {
            String amountStr = tilSearchAmount.getEditText().getText().toString();
            if (!TextUtils.isEmpty(amountStr)) {
                try {
                    double amount = Double.parseDouble(amountStr);
                    bills = dbHelper.getBillsByAmount(amount);
                    adapter.updateData(bills);
                } catch (NumberFormatException e) {
                    Toast.makeText(this, "请输入有效的金额", Toast.LENGTH_SHORT).show();
                }
            } else {
                loadAllBills();
            }
            return true;
        });

        // 加载所有账单
        loadAllBills();
    }

    private void loadAllBills() {
        bills = dbHelper.getAllBills();
        adapter.updateData(bills);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_sqlite, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            finish();
            return true;
        } else if (itemId == R.id.action_add) {
            showAddOrEditDialog(null);
            return true;
        } else if (itemId == R.id.action_refresh) {
            loadAllBills();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showAddOrEditDialog(Bill bill) {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_add_bill, null);
        TextInputEditText etDescription = dialogView.findViewById(R.id.et_description);
        TextInputEditText etAmount = dialogView.findViewById(R.id.et_amount);

        if (bill != null) {
            etDescription.setText(bill.getDescription());
            etAmount.setText(String.valueOf(bill.getAmount()));
        }

        new AlertDialog.Builder(this)
                .setTitle(bill == null ? "添加账单" : "修改账单")
                .setView(dialogView)
                .setPositiveButton("确定", (dialog, which) -> {
                    String description = etDescription.getText().toString();
                    String amountStr = etAmount.getText().toString();

                    if (TextUtils.isEmpty(description) || TextUtils.isEmpty(amountStr)) {
                        Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    try {
                        double amount = Double.parseDouble(amountStr);
                        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
                                .format(new Date());

                        if (bill == null) {
                            // 添加新账单
                            Bill newBill = new Bill(description, amount, date);
                            dbHelper.addBill(newBill);
                        } else {
                            // 更新现有账单
                            bill.setDescription(description);
                            bill.setAmount(amount);
                            bill.setDate(date);
                            dbHelper.updateBill(bill);
                        }

                        loadAllBills();
                        Toast.makeText(this, bill == null ? "添加成功" : "修改成功", Toast.LENGTH_SHORT).show();
                    } catch (NumberFormatException e) {
                        Toast.makeText(this, "请输入有效的金额", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    public void onEditClick(Bill bill) {
        showAddOrEditDialog(bill);
    }

    @Override
    public void onDeleteClick(Bill bill) {
        new AlertDialog.Builder(this)
                .setTitle("删除账单")
                .setMessage("确定要删除这条账单记录吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    dbHelper.deleteBill(bill.getId());
                    loadAllBills();
                    Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }
} 